package down.xiaoheihe.work;

import com.alibaba.fastjson.JSON;
import down.xiaoheihe.work.Entity.*;
import down.xiaoheihe.work.Mapper.MsgMapper;
import down.xiaoheihe.work.Mapper.MsghistoryMapper;
import down.xiaoheihe.work.Mapper.UserMapper;
import down.xiaoheihe.work.Response.MsgR;
import down.xiaoheihe.work.Response.msgS;
import down.xiaoheihe.work.utils.CurPool;
import down.xiaoheihe.work.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket的处理类。
 * 作用相当于HTTP请求
 * 中的controller
 */
@Component
@Slf4j
@CrossOrigin
@ServerEndpoint("/websocket/{fromId}/{toId}")
public class WebSocketServer {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MsgMapper msgMapper;
    @Autowired
    private MsghistoryMapper msghistoryMapper;
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static AtomicInteger onlineCount = new AtomicInteger();
    /**concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private Integer fromIdT;
    private Integer toIdT;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="fromId") String fromId, @PathParam(value="toId")String toId) {
        this.session = session;
        this.fromIdT= Integer.valueOf(fromId);
        this.toIdT= Integer.valueOf(toId);
        if(CurPool.webSocketPol.containsKey(fromIdT)){
            CurPool.webSocketPol.remove(fromIdT);
            CurPool.webSocketPol.put(fromIdT,this);
        }else{
            CurPool.webSocketPol.put(fromIdT,this);
            onlineCount.addAndGet(1);
        }
        log.info("用户连接:"+fromIdT+",当前在线人数为:" + onlineCount.get());
        if (msghistoryMapper == null){
            this.msghistoryMapper = (MsghistoryMapper) SpringContextUtil.getBean("msghistoryMapper");
        }
        if (userMapper == null){
            this.userMapper = (UserMapper) SpringContextUtil.getBean("userMapper");
        }
        if (msgMapper == null){
            this.msgMapper = (MsgMapper) SpringContextUtil.getBean("msgMapper");
        }
        List<Integer> integers = Arrays.asList(fromIdT, toIdT);
        MsghistoryExample msghistoryExample = new MsghistoryExample();
        msghistoryExample.createCriteria().andFromidIn(integers).andToidIn(integers);
        List<Msghistory> msghistories = msghistoryMapper.selectByExample(msghistoryExample);
        if (msghistories.size() == 0) {
            Msghistory msghistory1 = new  Msghistory();
            msghistory1.setFromid(fromIdT);
            msghistory1.setToid(toIdT);
            msghistoryMapper.insert(msghistory1);
            Msghistory msghistory2 = new  Msghistory();
            msghistory2.setToid(fromIdT);
            msghistory2.setFromid(toIdT);
            msghistoryMapper.insert(msghistory2);
        }
        MsgExample msgExample = new MsgExample();
        msgExample.createCriteria().andFromIdIn(integers).andToIdIn(integers);
        List<Msg> msgs = msgMapper.selectByExample(msgExample);
        List<MsgR> msgRs = new ArrayList<>();
        for (Msg msg : msgs) {
            MsgR msgR = new MsgR(msg);
            User tUser = userMapper.selectByPrimaryKey(msgR.getFromId());
            msgR.setImage(tUser.getImage());
            msgRs.add(msgR);
        }
        for (MsgR msgR : msgRs) {
            sendMessage(msgR);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(CurPool.webSocketPol.containsKey(fromIdT)){
            CurPool.webSocketPol.remove(fromIdT);
            onlineCount.addAndGet(-1);
        }
        log.info("用户退出:"+fromIdT+",当前在线人数为:" + onlineCount.get());
    }

    /**
     * 收到客户端消
     * 息后调用的方法
     * @param message
     * 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message) {
        msgS msg = JSON.parseObject(message, msgS.class);
        if (msg.getContent().equals("")){
            return;
        }
        Msg a = new Msg();
        a.setFromId(msg.getFromId());
        a.setToId(msg.getToId());
        a.setContent(msg.getContent());
        msgMapper.insert(a);
        MsgR msgR = new MsgR();
        Integer fromId = msg.getFromId();
        msgR.setFromId(fromId);
        msgR.setToId(msg.getToId());
        User tUser = userMapper.selectByPrimaryKey(fromId);
        msgR.setImage(tUser.getImage());
        msgR.setContent(msg.getContent());
        if (CurPool.webSocketPol.containsKey(msg.getToId())){
            WebSocketServer toServer = CurPool.webSocketPol.get(msg.getToId());
            toServer.sendMessage(msgR);
        }
        sendMessage(msgR);
        log.info("用户消息:"+fromIdT+",报文:"+msg.toString());
    }

    /**
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.error("用户错误:"+this.fromIdT+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object message) {
        try {
            this.session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

